//
//  ReplyTableViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "ReplyTableViewController.h"
#import "ReplyModel.h"
#import "ReplyTableViewCell.h"
#import "LoginViewController.h"
#import "UserInfoModel.h"

@interface ReplyTableViewController ()<UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate>
{
    int keyboardHeight;
    BOOL keyboardIsShowing;
}

@property(nonatomic,strong)NSMutableArray *modelArray;
@property (nonatomic, strong) UIView *footerView;// 底部视图
@property (nonatomic, strong) UIImageView *footerImageView; //底部视图背景图片
@property (nonatomic, strong) UITableView *tableView; // tableView
@property (nonatomic, strong) UITextField *textField; //评论文本框
@property (nonatomic, strong) UIButton *sendButton; //发送信息按钮


@property (nonatomic, strong) UIImageView *imageView; //没有评论时显示图片



@end

@implementation ReplyTableViewController
- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        self.modelArray = [[NSMutableArray alloc]init];
    }
    return _modelArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self getRequest];
    [self loadNavigationInfo]; // 设置导航栏信息
    [self createTableView]; //创建TvaleView
    [self createFooterView];     // 创建底部视图

    #pragma mark - 判断评论数是否等于0
    if ([self.commentsCount isEqualToString:@"0"])
    {
        self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, kScreenHeight / 4, kScreenWidth - 20, 100)];
        self.imageView.image = [UIImage imageNamed:@"atxt_no_liuyan"];
        [self.view addSubview:_imageView];
    }
}

#pragma mark - 设置导航栏
- (void)loadNavigationIndfo
{
    
    self.navigationItem.title = @"设置";
    // 取消
    UIBarButtonItem *leftBackButton = [UIBarButtonItem itemWithTarget:self Action:@selector(backAction) image:@"home_back" highImage:@"home_back_highlighted"];
    self.navigationItem.leftBarButtonItem = leftBackButton;

}

#pragma mark - 设置导航栏信息
- (void)loadNavigationInfo
{
    // 导航栏颜色
    self.navigationController.navigationBar.barTintColor = [UIColor RGBColor:71 green:128 blue:208 alpha:1];
    
    self.navigationItem.title = @"评论";

    // 返回
    UIBarButtonItem *leftBackButton = [UIBarButtonItem itemWithTarget:self Action:@selector(backAction) image:@"home_back" highImage:@"home_back_highlighted"];
    self.navigationItem.leftBarButtonItem = leftBackButton;
    
    // 标题
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    self.tableView.tableFooterView = [[UIView alloc] init];
}

#pragma mark - 创建底部视图 评论
- (void)createFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49)];
    footerView.backgroundColor = [UIColor RGBColor:236 green:236 blue:236 alpha:1];

    
    // 文本背景图片
    UIImageView *footerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, kScreenWidth - 20, 39)];
    footerImageView.image = [UIImage imageNamed:@"search"];
    footerImageView.userInteractionEnabled = YES;
    [footerView addSubview:footerImageView];
    self.footerImageView = footerImageView;
    
    // 文本框
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, footerImageView.width, 39)];
    self.textField.placeholder = @"写点什么...";
    self.textField.delegate = self;
    self.textField.font = [UIFont systemFontOfSize:14];
    [self.textField addTarget:self action:@selector(textFieldAction:) forControlEvents:UIControlEventEditingChanged];
    [footerImageView addSubview:_textField];

    // 发送按钮
    CGRect sendButtonFrame = CGRectMake(_textField.width + _textField.x + 5, 0, kScreenWidth - _footerImageView.width - 20, footerView.height);
    self.sendButton = [UIButton buttonWithFrame:sendButtonFrame title:@"发送" backgroundColor:nil];
    [self.sendButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    self.sendButton.showsTouchWhenHighlighted = YES;
//    self.sendButton.backgroundColor = [UIColor redColor];
    [self.sendButton addTarget:self action:@selector(sendButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:_sendButton];

    self.footerView = footerView;
    [self.view addSubview:footerView];
}

#pragma mark - 返回按钮
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 解析
- (void)getRequest
{
    [LORequestManger GET:self.urlString success:^(id response) {
        NSDictionary *bigDic = (NSDictionary *)response;
        NSArray *data = bigDic[@"data"];
        for (NSDictionary *dic in data) {
            ReplyModel *model = [ReplyModel modelWithDict:dic];
            [self.modelArray addObject:model];
        }
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@",error);
        [ProgressHUD progressHUD:self.view labelText:@"加载失败"];
    }];
}

#pragma mark - 发送按钮
- (void)sendButtonAction
{
    // 从数据库取出数据 
        NSMutableArray *userInfoArray = [FMDBManage selectAllUserInfo];
        UserInfoModel *userInfoModel = [userInfoArray objectAtIndex:0];
    
        // 获取文本框内容
        NSString *stringText = self.textField.text;
        ReplyModel *replModel = [[ReplyModel alloc] init];
        replModel.body = stringText; // 评论内容
        replModel.nickName = userInfoModel.nickname;
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:replModel.nickName,@"nickName", [TheThirdCall theThirdCallShare].avatarImageUrl, @"avatar", nil];
        replModel.user = dic;
        [self.modelArray addObject:replModel];
    
        // 刷新数据
        [self.tableView reloadData];
    
        // 改变frame
        self.footerImageView.width = kScreenWidth - 20;
        // 改变buttonframe
        self.sendButton .frame = CGRectMake(_footerImageView.width + _footerImageView.x + 5, 0, kScreenWidth - _footerImageView.width - 20, self.footerView.height);
        [self textFieldShouldReturn:self.textField]; // 键盘回收
        self.textField.text = @""; // 数据清空
        [self.imageView removeFromSuperview]; // 移除没有评论的图片

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.modelArray.count;
}

/**
 *  返回cell
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView registerClass:[ReplyTableViewCell class] forCellReuseIdentifier:@"reply"];
    ReplyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reply"];
    ReplyModel *model = self.modelArray[indexPath.row];
    [cell setModel:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReplyModel *model = self.modelArray[indexPath.row];
    return [ReplyTableViewCell heightForCell:model];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    [self textFieldShouldReturn:self.textField];
}


#pragma mark - 在视图即将消失的时候移除检测键盘通知
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 移除键盘弹出通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    
    // 移除键盘回收通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

#pragma mark - 在界面即将出现的时候,添加观察键盘是否弹出的通知
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    
    // 键盘回收
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - 当键盘开启的时候
// //在遇到有输入的情况下。由于现在键盘的高度是动态变化的。中文输入与英文输入时高度不同。所以输入框的位置也要做出相应的变化
- (void)keyBoardShow:(NSNotification *)aNotification
{
    // 先得到键盘的高度
    NSDictionary* info = [aNotification userInfo];
    //kbSize为键盘的尺寸 (有width, height)
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度

    #pragma mark - 判断键盘的高度是哪个··216 和252
    if (kbSize.height == 216)
    {
        // 改变底部视图的y值
        self.footerView.y = kScreenHeight - kbSize.height - 49;
    }
    else
    {
        self.footerView.y = kScreenHeight - kbSize.height - 49;
    }

}

#pragma mark - 键盘恢复原样
- (void)keyBoardHide:(NSNotification *)aNotification
{
    self.footerView.y = kScreenHeight - 49;    
}

#pragma mark - textField代理方法 键盘回收
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}

#pragma mark -改变的内容的时候触发方法
- (void)textFieldAction:(UITextField *)textField
{
    if (textField.text.length != 0)
    {
        // 改变frame
        self.footerImageView.width = kScreenWidth - 60;
        
        // 改变buttonframe
        self.sendButton .frame = CGRectMake(self.footerImageView.x + self.footerImageView.width + 10, 0, kScreenWidth - self.footerImageView.width - 20, self.footerView.height);
    }
    else
    {
//        YAXLog(@"000");
        // 改变frame
        self.footerImageView.width = kScreenWidth - 20;
        
        // 改变buttonframe
        self.sendButton .frame = CGRectMake(_footerImageView.width + _footerImageView.x + 5, 0, kScreenWidth - _footerImageView.width - 20, self.footerView.height);
    }

}


#pragma mark - 开始编辑时触发
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    // 判断登陆状态
    // 先取出登陆状态
    NSString *loginStatus = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginStatus];
    if ([loginStatus isEqualToString:@"YES"])
    {
        [self keyBoardShow:nil];
    }
    else // 跳转到登录
    {
        // 跳转到登陆页面
        LoginViewController *loginViewVc = [[LoginViewController alloc] init];
        //            [self.navigationController pushViewController:loginStatus animated:YES];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginViewVc];
        nav.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:nav animated:YES completion:nil];
        [self keyBoardHide:nil];
        
    }
}

#pragma mark - 内容警告提示
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}


@end
